<template>
  <div class="movie-detail-container">
    <div class="movie-header">
      <button @click="goBack" class="back-btn">← 返回</button>
    </div>

    <div class="movie-detail-content">
      <!-- 电影海报 -->
      <div class="poster-container">
        <img
          :src="movieDetail.movieImage"
          :alt="movieDetail.movieName"
          class="poster"
        />
      </div>

      <!-- 电影信息 -->
      <div class="movie-info">
        <h1 class="movie-title">
          {{ movieDetail.movieName }}
          <span class="original-title" v-if="movieDetail.originalTitle"
            >({{ movieDetail.originalTitle }})</span
          >
        </h1>

        <!-- 电影类型、上映地点、时长、上映时间 -->
        <div class="movie-basic-info">
          <span class="movie-type">{{ movieDetail.type || "未知类型" }}</span>
          <span class="separator">|</span>
          <span class="release-location">{{
            movieDetail.releaseLocation || "未知地区"
          }}</span>
          <span class="separator">|</span>
          <span class="duration"
            >{{ movieDetail.duration || "未知时长" }}分钟</span
          >
          <div class="release-date">
            上映时间：{{ movieDetail.releaseTime || "未知上映时间" }}
          </div>
        </div>

        <!-- 评分和票房 -->
        <div class="score-box">
          <div class="score">
            <span class="score-value">{{
              movieDetail.movieScore || "暂无评分"
            }}</span>
            <span class="score-text">评分</span>
          </div>
          <div class="box-office">
            <span class="box-office-value">{{
              movieDetail.boxOffice || "0"
            }}</span>
            <span class="box-office-text">票房(万)</span>
          </div>
        </div>

        <!-- 演职人员 -->
        <div class="cast">
          <h3>演职人员</h3>
          <div class="director">
            <span class="label">导演：</span>
            <span class="value">{{ movieDetail.director || "未知导演" }}</span>
          </div>
          <div class="actors">
            <span class="label">演员：</span>
            <span class="value">{{ movieDetail.actors || "未知演员" }}</span>
          </div>
        </div>

        <!-- 剧情简介 -->
        <div class="synopsis">
          <h3>剧情简介</h3>
          <p>{{ movieDetail.movieIntro || "暂无剧情简介" }}</p>
        </div>

        <!-- 购票按钮 -->
        <button @click="goToCinemaDetail()" class="buy-ticket-btn">
          立即购票
        </button>
      </div>
    </div>

    <!-- ========== 评论区域 ========== -->
    <div class="comment-section">
      <h3>观众热评</h3>

      <!-- 发表评论 -->
      <div class="comment-input">
        <textarea
          v-model="newComment"
          placeholder="说说你的观影感受吧~"
        ></textarea>
        <button @click="submitComment">发布评论</button>
      </div>

      <!-- 评论树（父层） -->
      <div class="comment-list">
        <div class="comment-item" v-for="item in comments" :key="item.id">
          <div class="comment-content">
            <strong>用户{{ item.userId }}</strong
            >：{{ item.content }}
            <div class="comment-meta">
              <span>{{ formatTime(item.createTime) }}</span>
            </div>
          </div>

          <div class="comment-actions">
            <span @click="like(item.id)">👍 {{ item.likes || 0 }}</span>
            <span @click="showReply(item.id, null)">💬 回复</span>
          </div>

          <!-- 回复输入框（父评论） -->
          <div
            class="reply-box"
            v-if="activeReplyId === item.id && !activeReplyTo"
          >
            <textarea
              v-model="replyContent"
              placeholder="回复 用户{{ item.userId  }}..."
            ></textarea>
            <button @click="submitReply(item.id)">发送</button>
            <button @click="cancelReply" class="cancel-btn">取消</button>
          </div>

          <!-- 子回复（递归展示所有层级） -->
          <div
            class="replies-container"
            v-if="item.children && item.children.length > 0"
          >
            <div
              class="reply-item"
              v-for="(child, index) in visibleReplies(item)"
              :key="child.id"
            >
              <div class="comment-content">
                <strong>用户{{ child.userId }}</strong>
                <span v-if="child.parentUsername">
                  回复 {{ child.parentUsername }}：</span
                >
                {{ child.content }}
                <div class="comment-meta">
                  <span>{{ formatTime(child.createTime) }}</span>
                </div>
              </div>

              <div class="comment-actions">
                <span @click="like(child.id)">👍 {{ child.likes || 0 }}</span>
                <span @click="showReply(child.id, child.username)"
                  >💬 回复</span
                >
              </div>

              <!-- 子回复输入框 -->
              <div class="reply-box" v-if="activeReplyId === child.id">
                <textarea
                  v-model="replyContent"
                  placeholder="回复 用户{{ child.userId  }}..."
                ></textarea>
                <button @click="submitReply(child.id)">发送</button>
                <button @click="cancelReply" class="cancel-btn">取消</button>
              </div>

              <!-- 递归展示子回复的子回复 -->
              <div
                class="nested-replies"
                v-if="child.children && child.children.length > 0"
              >
                <div
                  class="reply-item nested"
                  v-for="(grandchild, gIndex) in visibleReplies(child)"
                  :key="grandchild.id"
                >
                  <div class="comment-content">
                    <strong>用户{{ grandchild.userId }}</strong>
                    <span v-if="grandchild.parentUsername">
                      回复 {{ grandchild.parentUsername }}：</span
                    >
                    {{ grandchild.content }}
                    <div class="comment-meta">
                      <span>{{ formatTime(grandchild.createTime) }}</span>
                    </div>
                  </div>

                  <div class="comment-actions">
                    <span @click="like(grandchild.id)"
                      >👍 {{ grandchild.likes || 0 }}</span
                    >
                    <span @click="showReply(grandchild.id, grandchild.username)"
                      >💬 回复</span
                    >
                  </div>

                  <!-- 嵌套回复输入框 -->
                  <div class="reply-box" v-if="activeReplyId === grandchild.id">
                    <textarea
                      v-model="replyContent"
                      placeholder="回复 用户: {{ grandchild.userId  }}..."
                    ></textarea>
                    <button @click="submitReply(grandchild.id)">发送</button>
                    <button @click="cancelReply" class="cancel-btn">
                      取消
                    </button>
                  </div>
                </div>

                <!-- 嵌套回复的展开/收起按钮 -->
                <div
                  v-if="child.children.length > 2"
                  class="toggle-replies"
                  @click="toggleReplies(child.id)"
                >
                  {{
                    expandedReplies[child.id]
                      ? "收起回复"
                      : `展开更多回复（${child.children.length - 2}）`
                  }}
                </div>
              </div>
            </div>

            <!-- 父评论的回复展开/收起按钮 -->
            <div
              v-if="item.children.length > 2"
              class="toggle-replies"
              @click="toggleReplies(item.id)"
            >
              {{
                expandedReplies[item.id]
                  ? "收起回复"
                  : `展开更多回复（${item.children.length - 2}）`
              }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getMovieDetail } from "@/api/movie";
import {
  getCommentsByMovieId,
  postComment,
  replyComment,
  likeComment,
} from "@/api/comment";

const movieDetail = ref({});
const route = useRoute();
const router = useRouter();
const expandedReplies = ref({}); // { commentId: boolean }

// 评论相关变量
const comments = ref([]);
const newComment = ref(""); // 顶层输入内容
const replyContent = ref(""); // 回复输入内容
const activeReplyId = ref(""); // 当前正在回复哪条评论
const activeReplyTo = ref(null); // 正在回复的用户名

onMounted(() => {
  const movieId = route.query.movieId;
  if (movieId) {
    fetchMovieDetail(movieId);
    loadComments();
  } else {
    console.error("未获取到电影ID");
  }
});

async function fetchMovieDetail(movieId) {
  try {
    const response = await getMovieDetail(movieId);
    if (response.data.code === 200) {
      movieDetail.value = response.data.data || {};
      console.log("电影详情数据：", movieDetail);
      console.log("电影详情数据：", movieDetail.value);
    } else {
      console.error("获取电影详情失败:", response.data.message);
    }
  } catch (error) {
    console.error("请求异常:", error);
  }
}

const goBack = () => {
  router.back();
};

// 点击立即购票时跳转到 CinemaDetail 页面
function goToCinemaDetail() {
  const defaultCinemaId = 1;
  const cinemaId = defaultCinemaId;
  const movie = movieDetail.value;
  if (!movie.movieId) {
    console.error("❌ 无法获取 movieId");
    return;
  }

  router.push({
    path: `/cinemaDetail/${cinemaId}`,
    query: {
      movieId: movie.movieId,
      movieName: movie.movieName,
      moviePoster: movie.movieImage,
      movieScore: movie.movieScore,
      duration: movie.duration,
      actors: movie.actors,
    },
  });
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return "";
  const date = new Date(time);
  return date.toLocaleString();
};

// 获取评论树
const loadComments = async () => {
  const movieId = route.query.movieId;
  if (!movieId) return;
  try {
    const res = await getCommentsByMovieId(movieId);
    comments.value = res.data || [];
  } catch (error) {
    console.error("获取评论失败:", error);
  }
};

// 发布评论
const submitComment = async () => {
  if (!newComment.value.trim()) return;

  const userId = localStorage.getItem("userId");
  if (!userId) {
    alert("请先登录");
    return;
  }

  try {
    await postComment({
      movieId: route.query.movieId,
      userId,
      content: newComment.value,
    });
    newComment.value = "";
    loadComments(); // 重新加载评论
  } catch (error) {
    console.error("发布评论失败:", error);
    alert("发布评论失败，请重试");
  }
};

// 展示回复框
const showReply = (id, toUsername) => {
  activeReplyId.value = id;
  activeReplyTo.value = toUsername;
};

// 取消回复
const cancelReply = () => {
  activeReplyId.value = "";
  activeReplyTo.value = null;
  replyContent.value = "";
};

// 提交回复
const submitReply = async (parentId) => {
  if (!replyContent.value.trim()) return;

  const userId = localStorage.getItem("userId");
  if (!userId) {
    alert("请先登录");
    return;
  }

  try {
    await replyComment(parentId, {
      userId,
      content: replyContent.value,
    });
    replyContent.value = "";
    activeReplyId.value = "";
    activeReplyTo.value = null;
    loadComments(); // 重新加载评论
  } catch (error) {
    console.error("回复失败:", error);
    alert("回复失败，请重试");
  }
};

// 切换回复展开/收起状态
const toggleReplies = (id) => {
  expandedReplies.value[id] = !expandedReplies.value[id];
};

// 控制显示的回复数量
const visibleReplies = (comment) => {
  if (!comment.children) return [];
  if (expandedReplies.value[comment.id]) return comment.children;
  return comment.children.slice(0, 2); // 默认只显示前 2 条
};

// 点赞
const like = async (id) => {
  const userId = localStorage.getItem("userId");
  if (!userId) {
    alert("请先登录");
    return;
  }

  try {
    await likeComment(id);
    loadComments(); // 重新加载评论以更新点赞数
  } catch (error) {
    console.error("点赞失败:", error);
    alert("点赞失败，请重试");
  }
};
</script>

<style scoped>
.movie-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Microsoft Yahei", sans-serif;
}

.movie-header {
  margin-bottom: 20px;
}

.back-btn {
  padding: 8px 15px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.movie-detail-content {
  display: flex;
  gap: 30px;
}

.poster-container {
  flex-shrink: 0;
}

.poster {
  width: 280px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.movie-info {
  flex-grow: 1;
  margin-left: 60px;
}

.movie-title {
  font-size: 28px;
  margin: 0 0 15px 0;
  color: #333;
}

.original-title {
  font-size: 20px;
  color: #666;
  margin-left: 10px;
}

.movie-basic-info {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
  line-height: 1.8;
}

.movie-type {
  color: #a2131d;
}

.separator {
  margin: 0 8px;
  color: #ccc;
}

.release-date {
  margin-top: 5px;
}

.score-box {
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.score .score-value {
  font-size: 36px;
  color: #a2131d;
  font-weight: bold;
}

.score .score-text {
  font-size: 16px;
  color: #666;
  margin-left: 5px;
}

.box-office .box-office-value {
  font-size: 24px;
  color: #333;
  font-weight: bold;
}

.box-office .box-office-text {
  font-size: 16px;
  color: #666;
  margin-left: 5px;
}

.cast {
  margin-bottom: 30px;
}

.cast h3 {
  font-size: 20px;
  margin: 0 0 15px 0;
  color: #333;
  border-left: 4px solid #a2131d;
  padding-left: 10px;
}

.director,
.actors {
  margin-bottom: 10px;
  line-height: 1.6;
}

.label {
  display: inline-block;
  width: 60px;
  color: #666;
  font-weight: bold;
}

.value {
  color: #333;
}

.synopsis {
  margin-bottom: 30px;
}

.synopsis h3 {
  font-size: 20px;
  margin: 0 0 15px 0;
  color: #333;
  border-left: 4px solid #a2131d;
  padding-left: 10px;
}

.synopsis p {
  line-height: 1.8;
  color: #333;
  text-indent: 2em;
}

.buy-ticket-btn {
  padding: 12px 30px;
  background-color: #a2131d;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.buy-ticket-btn:hover {
  background-color: #a2131d;
}

.comment-section {
  margin-top: 40px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}

.comment-input textarea,
.reply-box textarea {
  width: 100%;
  height: 70px;
  padding: 10px;
  border-radius: 6px;
  border: 1px solid #ddd;
  margin-bottom: 10px;
}

.comment-input button,
.reply-box button {
  background: #a2131d;
  color: white;
  border: none;
  padding: 6px 14px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.reply-box .cancel-btn {
  background: #999;
}

.comment-item {
  border-bottom: 1px solid #eee;
  padding: 12px 0;
}

.comment-content {
  margin-bottom: 8px;
}

.comment-meta {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.reply-item {
  margin-left: 30px;
  padding: 10px 0;
  border-left: 2px solid #eee;
}

.reply-item.nested {
  margin-left: 60px;
  border-left-color: #ddd;
}

.comment-actions span {
  margin-right: 15px;
  cursor: pointer;
  font-size: 13px;
  color: #666;
}

.comment-actions span:hover {
  color: #a2131d;
}

.toggle-replies {
  margin-left: 30px;
  font-size: 13px;
  color: #a2131d;
  cursor: pointer;
  margin-top: 4px;
  margin-bottom: 10px;
}

.toggle-replies:hover {
  text-decoration: underline;
}

.replies-container {
  margin-top: 10px;
}

.nested-replies {
  margin-top: 10px;
}
</style>
